package com.gjy.sql.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.concurrent.RecursiveAction;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-03-05 19:46:47
 */
public class BatchInsertAction extends RecursiveAction {
    // 单次批处理的最大SQL数量阈值
    private static final int THRESHOLD = 100;
    private final List<String> sqlList;
    private final int start;
    private final int end;
    private final String dbUrl;
    private final String username;
    private final String password;

    public BatchInsertAction(List<String> sqlList, int start, int end,
                             String dbUrl, String username, String password) {
        this.sqlList = sqlList;
        this.start = start;
        this.end = end;
        this.dbUrl = dbUrl;
        this.username = username;
        this.password = password;
    }

    @Override
    protected void compute() {
        // 如果任务量小于阈值，直接执行批处理
        if (end - start <= THRESHOLD) {
            executeBatch(sqlList.subList(start, end));
        } else {
            // 拆分任务为左右两部分
            int mid = (start + end) / 2;
            BatchInsertAction leftTask = new BatchInsertAction(sqlList, start, mid, dbUrl, username, password);
            BatchInsertAction rightTask = new BatchInsertAction(sqlList, mid, end, dbUrl, username, password);
            invokeAll(leftTask, rightTask); // 并行执行子任务
        }
    }

    // 执行实际的批处理操作
    private void executeBatch(List<String> batchSql) {
        try (Connection conn = DriverManager.getConnection(dbUrl, username, password);
             Statement stmt = conn.createStatement()) {
            conn.setAutoCommit(false); // 关闭自动提交
            for (String sql : batchSql) {
                stmt.addBatch(sql); // 添加SQL到批处理
            }
            stmt.executeBatch(); // 执行批处理
            conn.commit(); // 提交事务
        } catch (SQLException e) {
            e.printStackTrace();
            // 可根据需求回滚事务或记录错误日志
        }
    }
}